package com.getpebble.android.framework.endpoint;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundSystemMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundSystemMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundSystemMessage.SysMsgCommand;
import com.google.common.collect.ImmutableSet;
import java.util.Set;

public class SystemMessageEndpoint extends Endpoint {
    private static final String TAG = SystemMessageEndpoint.class.getSimpleName();
    private Listener mListener;
    private IEndpointMessageSender mMessageSender;

    public interface Listener {
        void onSystemMessage(PblInboundSystemMessage pblInboundSystemMessage);
    }

    public SystemMessageEndpoint(IEndpointMessageSender messageSender) {
        if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender' cannot be null");
        }
        this.mMessageSender = messageSender;
    }

    public void setListener(Listener listener) {
        this.mListener = listener;
    }

    private Listener getListener() {
        return this.mListener;
    }

    private IEndpointMessageSender getMessageSender() {
        return this.mMessageSender;
    }

    Set<EndpointId> getSupportedEndpoints() {
        return ImmutableSet.of(EndpointId.SYSTEM_MESSAGE);
    }

    private boolean isSupportedEndpointId(EndpointId endpointId) {
        return getSupportedEndpoints().contains(endpointId);
    }

    public void sendSystemMessage(SysMsgCommand command) {
        getMessageSender().sendMessage(new PblOutboundSystemMessage(command));
    }

    boolean onReceive(ProtocolMessage protocolMessage) {
        if (!isSupportedEndpointId(EndpointId.fromCode(protocolMessage.getEndpointId()))) {
            return false;
        }
        try {
            PblInboundSystemMessage systemMessage = new PblInboundSystemMessage(protocolMessage);
            if (systemMessage.getType() == null) {
                Trace.warning(TAG, "Received a system message with unsupported type; dropping");
                return true;
            }
            Listener listener = getListener();
            if (listener == null) {
                return true;
            }
            listener.onSystemMessage(systemMessage);
            return true;
        } catch (IllegalArgumentException e) {
            Trace.warning(TAG, "Received invalid system message", e);
            return true;
        }
    }
}
